﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using agent02.Model;

namespace agent02.Controllers
{
    public class AccountController : Controller
    {
        AgentDBEntities db = new AgentDBEntities();
        //
        // GET: /Account/
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(TAI_KHOAN tk)
        {
            if (ModelState.IsValid)
            {
                var acc = from a in db.TAI_KHOAN
                          where (a.TrangThai == 1) && (a.Username.Equals(tk.Username)) && (a.Password.Equals(tk.Password))
                          select a;
                if (acc.Count() == 1)
                {
                    FormsAuthentication.SetAuthCookie(tk.Username, false);
                    // NHAN_VIEN or KHACH_HANG?
                    if (acc.Single().NHAN_VIEN.Any())
                    {
                        return RedirectToAction("Index", "Admin");
                    }
                    else if (acc.Single().KHACH_HANG.Any())
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }
            // something wrong
            return View(tk);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

    }
}
